package com.hegongda.okcmall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.hegongda.okcmall.product.vo.Catelog2Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hegongda.common.utils.PageUtils;
import com.hegongda.common.utils.Query;

import com.hegongda.okcmall.product.dao.CategoryDao;
import com.hegongda.okcmall.product.entity.CategoryEntity;
import com.hegongda.okcmall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        return baseMapper.listWithTree();
    }

    @Override
    public void deleteMenuByIds(Long[] catIds) {
        baseMapper.deleteBatchIds(Arrays.asList(catIds));
    }

    @Override
    public List<CategoryEntity> listTree() {
//        //1、查出所有分类
//        List<CategoryEntity> entities = baseMapper.selectList(null);
//        entities.stream().forEach(item -> System.out.println(item.getName()));
//        //2、组装成父子的树形结构
//
//        //2.1）、找到所有的一级分类
//        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
//                categoryEntity.getParentCid() == 0
//        ).map((menu)->{
//            menu.setChildren(getChildrens(menu,entities));
//            return menu;
//        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());


        //1、查出所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2、组装成父子的树形结构

        //2.1）、找到所有的一级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return level1Menus;
    }

    @Override
    public Long[] getCategoryPath(Long catelogId) {
        List<Long> ids = new ArrayList<>();
        CategoryEntity entity = this.baseMapper.selectById(catelogId);
        if (entity != null) {
            setCategoryIds(entity.getCatId(), ids);
        }
        Collections.reverse(ids);
        return (Long[]) ids.toArray(new Long[ids.size()]);
    }

    @Override
    public CategoryEntity selectById(Long catalogId) {
        return this.selectOne(catalogId);
    }

    /*
         缓存说明： 默认生成一个key , 并且缓存永远不会过期， value值经过jdk进行序列化存到redis中
     */
    // 查询商品的一级分类
    // 自定义生成key,指定
    @Cacheable({"category"})   // 进行缓存
    @Override
    public List<CategoryEntity> queryCategoryLevel() {
        System.out.println("第一次进行查询");
        List<CategoryEntity> categoryEntities = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return categoryEntities;
    }

    /**
     * 获取一级分类下的所有二级分类
     * 通过redis进行缓存
     *
     * @return
     */
    // TODO 在高并发情况下会出现堆外内存溢出 OutOfDirectMemoryError
    /*
        引起原因： 1、springboot2.0 以后用lettuce 客户端，该客户端通过netty作为网络通信，导致不能及时回收堆外内存
                   解决方式： 用jedis客户端

         缓存存在的问题：
              缓存穿透 ： 查询不存在的数据，直接访问mysql数据    对空结果进行缓存
              缓存击穿 ： 热点key在某一个时间过期，此时刻大量请求访问这一数据  加锁解决
              缓存雪崩 ： 大量数据在同一时刻全部过期   设置不同的过期时间
     */
    @Override
    public Map<String, List<Catelog2Vo>> getCatelog2() {
        String catelogJson = stringRedisTemplate.opsForValue().get("catelogJson");
        if (StringUtils.isEmpty(catelogJson)) {
            return lockWithRedisson();
        }
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catelogJson, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;

    }

    public Map<String, List<Catelog2Vo>> lockWithRedisson() {
        RLock lock = redissonClient.getLock("category-lock");
        lock.lock();
        try {
            Map<String, List<Catelog2Vo>> catelog2 = getCatelog2s();
            return catelog2;
        } finally {
            lock.unlock();
        }

    }

    public Map<String, List<Catelog2Vo>> lockWithRedis() {
        String token = UUID.randomUUID().toString();
        Boolean isLock = stringRedisTemplate.opsForValue().setIfAbsent("lock", token, 300L, TimeUnit.SECONDS);
        if (isLock) {
            try {
                Map<String, List<Catelog2Vo>> catelog2 = getCatelog2s();
                return catelog2;
            } finally {
                // 进行释放锁， 原子操作，查看锁是否已经过期，
                String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
                stringRedisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("lock"), token);
            }
        } else {
            // 进行自旋重试
            return lockWithRedis();
        }
    }

    public Map<String, List<Catelog2Vo>> getCatelog2s() {
        // 查询出所有
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        // 查询一级分类
        List<CategoryEntity> categoryEntities = getCategoryByParent(selectList, 0L);
        List<Long> level1Ids = categoryEntities.stream()
                .map(categoryEntity -> categoryEntity.getCatId())
                .collect(Collectors.toList());
        Map<String, List<Catelog2Vo>> collect = level1Ids.stream().collect(Collectors.toMap(k -> k.toString(), v -> {

            // 查询二级分类
            List<CategoryEntity> level2 = getCategoryByParent(selectList, v); //baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v));
            List<Catelog2Vo> catelog2VoList = null;
            if (level2 != null && level2.size() > 0) {
                catelog2VoList = level2.stream().map(L2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.toString(), null, L2.getCatId().toString(), L2.getName());
                    // 查询三级分类
                    List<CategoryEntity> level3 = getCategoryByParent(selectList, L2.getCatId());// baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", L2.getCatId()));
                    List<Catelog2Vo.Catelog3Vo> collect3 = null;
                    if (level3 != null && level3.size() > 0) {
                        collect3 = level3.stream().map(L3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(L2.getCatId().toString(), L3.getCatId().toString(), L3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                    }
                    catelog2Vo.setCatalog3List(collect3);
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
        String jsonData = JSON.toJSONString(collect);
        stringRedisTemplate.opsForValue().set("catelogJson", jsonData);
        return collect;
    }


    public List<CategoryEntity> getCategoryByParent(List<CategoryEntity> categoryEntities, Long parentCid) {
        return categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().longValue() == parentCid.longValue())
                .collect(Collectors.toList());
    }

    private void setCategoryIds(Long id, List<Long> ids) {
        ids.add(id);
        CategoryEntity categoryEntity = this.baseMapper.selectById(id);
        if (categoryEntity.getParentCid() != null && categoryEntity.getParentCid().longValue() != 0L) {
            setCategoryIds(categoryEntity.getParentCid(), ids);
        }
    }

    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid().longValue() == root.getCatId().longValue();
        }).map(categoryEntity -> {
            //1、找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted(Comparator.comparingInt(menu -> (menu.getSort() == null ? 0 : menu.getSort()))).collect(Collectors.toList());

        return children;
    }


    public CategoryEntity selectOne(Long catelogId) {
        return baseMapper.selectById(catelogId);
    }
}